package com.leyou.seckill.service;

import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.UserHolder;
import com.leyou.common.constants.MQConstants;
import com.leyou.seckill.pojo.SeckillStatEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author RudolfHugh
 * @since 2020/5/29 16:34
 */
@Slf4j
@Service
public class SeckillService {

  @Autowired private StringRedisTemplate stringRedisTemplate;

  @Autowired private AmqpTemplate amqpTemplate;


  public ResponseEntity<String> seckillItem(Long skuId) {

    //Redis计数器
    ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
    Long stock = operations.increment(skuId.toString(), -1);

    //计数器小于0代表库存不足,直接返回一个秒杀失败页面
    if (stock < 0) {
      return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }

    //库存充足，将请求发送到mq,获取用户信息
    UserInfo userInfo = UserHolder.getUser();
    //发送消息
    Map<String, Long> map = new HashMap<>();
    map.put("userId", userInfo.getId());
    map.put("skuId", skuId);
    map.put("stock",stock);
    amqpTemplate.convertAndSend(MQConstants.Exchange.SECKILL_EXCHANGE_NAME,MQConstants.RoutingKey.SECKILL_KEY,map);

    return ResponseEntity.ok("秒杀成功,正在给你生成订单");
  }





  // /**
  //  * 发送消息到秒杀队列当中
  //  *
  //  * @param seckillMessage
  //  */
  // public void sendMessage(Spu) {
  //   String json = JsonUtils.toString(seckillMessage);
  //   try {
  //     amqpTemplate.convertAndSend("order.seckill", json);
  //   } catch (Exception e) {
  //     log.error("秒杀商品消息发送异常，商品id：{}", seckillMessage.getSeckillItem().getSkuId(), e);
  //   }
  // }
}
